<template>
  <div>
    <div v-if="showPop" class="dialogBox">
      <div class="dialogContainer">
        <div class="dialogTitle">
          {{ voiceList.dataTypeName }}
          <i
            @click="closePop"
            class="el-icon-close"
            style="position: absolute; right: 1rem; cursor: pointer"
          ></i>
        </div>
        <hr />
        <div class="dialogText">
          时间：{{ voiceList.execuTime }}<br />
          内容：{{ voiceList.message }}
        </div>
        <!-- <div class="dialogButtonBox">
          <el-button
            type="success"
            round
            style="
              width: 4rem;
              font-size: 0.8rem;
              height: 2.2rem;
              text-align: center;
              padding: 0.2rem;
            "
            >语音</el-button
          >
          <el-button
            style="
              margin-left: 2.8rem;
              width: 4rem;
              font-size: 0.8rem;
              height: 2.2rem;
              text-align: center;
              padding: 0.2rem;
            "
            type="primary"
            round
            @click="changeTypeClick(2)"
            >视频</el-button
          >
        </div> -->
      </div>
    </div>
  </div>
</template>
  <script>
import { mapState, mapMutations } from "vuex";
//import callRoom from "@/components/call-room/index.vue";
import mqtt from "mqtt";
import {
  MQTT_SERVICE,
  MQTT_USERNAME,
  MQTT_PASSWORD,
} from "../../utils/sysconstant";
const appoptions = {
  connectTimeout: 40000,
  clientId: "appmqttjs_" + Math.random().toString(16).substr(2, 8),
  username: MQTT_USERNAME,
  password: MQTT_PASSWORD,
  clean: true,
};
import { trtcSpeech, getTrtcLogin } from "../../api/index";
//var speech = new SpeechSynthesisUtterance();
export default {
  name: "messageVoice",
  data() {
    return {
      messageVoice: "", //消息的语音
      voiceList: {
        id: 0, // 任务执行记录ID
        userId: "", // 住户ID
        dataTypeId: "", // 数据类型ID  数据类型，0：其他；1：报警记录；2：护理方案；3：提醒管理；4：体检报告；5：医生建议；6：慢病信息；7：护理内容；8：用药计划；9：综合评估
        dataTypeName: "标题", // 数据类型名称
        message: "暂未获取到内容", // 语音播报内容
        createTime: "", // 记录创建时间
        execuTime: "23：09", // 任务时间，如 23:09
      },
      changeType: 0, //选择了哪种通信方式：0：未选择展示弹窗  1：选择  2：视频
      showPop: false,
      appClient: null, //ws
      appwsConnected: false, //ws是否连接
    };
  },
  components: {
    //callRoom,
  },
  computed: {
    ...mapState({
      currentUserId: (state) => state.currentUserId, //当前的用户id
      userInfoDetails: (state) => state.userInfoDetails,
      loginUserInfo: (state) => state.loginUserInfo,
    }),
  },
  created() {
    //创建TRTC
    this.appmqttMSG();
  },
  destroyed() {
    console.log("****************销毁页面***************");
    this.appClient.end();
  },
  methods: {
    ...mapMutations([
      "setChangeType", //设置通讯类型
    ]),
    //关闭弹窗
    closePop() {
      this.showPop = false;
    },
    appmqttMSG() {
      console.log("**************appmqtt开始连接**************");
      let that = this;
      let currentUserId = this.currentUserId;
      // 创建mqtt客户端
      that.appClient = mqtt.connect(MQTT_SERVICE, appoptions);
      if (!that.appClient.connected) {
        // mqtt连接
        that.appClient.on("connect", (e) => {
          console.log(
            "**************appmqtt连接成功****************",
            e,
            currentUserId + "/voicebroadcast/request"
          );
          that.appwsConnected = true; //ws连接成功
          let topic = currentUserId + "/voicebroadcast/request";
          //连接成功后订阅消息
          that.appClient.subscribe(topic, { qos: 0 }, (error) => {
            if (!error) {
              console.log("**************订阅成功**************");
            } else {
              console.log("**************订阅失败**************");
            }
          });
        });
      }
      // 接收消息处理
      that.appClient.on("message", (topic, message) => {
        let data = JSON.parse(message);
        console.log("收到来自", topic, "的消息", data);
        that.voiceList.dataTypeName = data.DataTypeName || "标题";

        that.voiceList.execuTime = data.execuTime;
        //收到语音消息
        if (data.hasUrl == 1) {
          that.voiceList.message = "语音消息";
          that.playMeaageVoice(data.Url);
        } else {
          that.voiceList.message = data.Message;
          //收到文本消息
          that.playAudio(data.Message);
        }

        //开始语音播报
        //that.playMessage();
      });
      // 断开发起重连
      that.appClient.on("reconnect", (error) => {
        console.log("正在重连:", error);
      });
      //如果连接错误，打印错误
      that.appClient.on("error", function (err) {
        console.log("连接错误了 err=>", err);
        if (that.appwsConnected) {
          that.appClient.end();
        }
        that.appwsConnected = false;
      });
    },
    //登录TRTC
    async loginTrtc() {
      const params = {
        acount: "admin_nikoyose_3033654362",
        paswd: "admin_nikoyose_3033654362",
        appid: 1400552732,
      };
      await getTrtcLogin(params).then((res) => {
        if (res.data.code == 0) {
          //存储token
          window.localStorage["trtctoken"] = JSON.stringify(res.data.token);
          //存储token过期时间
          window.localStorage["trtcexpiration"] = JSON.stringify(
            res.data.expiration
          );
        } else {
          this.$message.error(res.error_msg);
        }
      });
    },
    //播放语音消息
    playMeaageVoice(url) {
      this.showPop = true;
      this.messageVoice = null;
      this.messageVoice = new Audio();
      this.messageVoice.src = url;
      this.messageVoice.play();
      //播放结束
      this.messageVoice.addEventListener("ended", () => {
        this.showPop = false;
      });
    },
    //播放音频
    async playAudio(data) {
      let trtcexpiration = JSON.parse(localStorage.trtcexpiration);
      let newdate = new Date().Format("yyyy-MM-dd hh:mm:ss");
      let trtcdate = new Date(trtcexpiration * 1000).Format(
        "yyyy-MM-dd hh:mm:ss"
      );
      console.log(
        "**********判断是否需要重新获取token*********",
        newdate,
        trtcdate,
        newdate >= trtcdate
      );
      //如果当前时间大于trtctoken失效时间，那么重新获取token
      if (newdate >= trtcdate) {
        console.log("****************重新获取token****************");
        this.loginTrtc();
      }
      let params = "message=" + data;
      let voiceSrc = "";
      await trtcSpeech(params)
        .then((res) => {
          console.log("调用接口的结果", res);
          if (res.data.code == 0) {
            voiceSrc = res.data.result;
            this.showPop = true;
          } else {
            this.$message.error("语音播报失败");
          }
        })
        .catch((error) => {
          console.log("获取失败", error);
          this.$message.error("语音播报失败");
        });
      this.messageVoice = null;
      this.messageVoice = new Audio();
      this.messageVoice.src = voiceSrc;
      // this.messageVoice.loop = "loop";
      this.messageVoice.play();
      setTimeout(() => {
        this.showPop = false;
      }, 5000);
    },
    //停止音频
    stopAudio() {
      console.log("停止音频", this.messageVoice);
      if (this.messageVoice != null) {
        this.messageVoice.pause();
      }
    },
    playMessage() {
      // //speech.pitch = 10 // 获取并设置话语的音调(值越大越尖锐,越低越低沉)
      // // speech.rate  = 5 // 获取并设置说话的速度(值越大语速越快,越小语速越慢)
      // //speech.voice = 5 // 获取并设置说话的声音
      // //speech.volume = 5 // 获取并设置说话的音量
      // // speech.lang = speechSynthesis.getVoices()[0] // 设置播放语言，测试没效果
      // // speech.cancel() // 删除队列中所有的语音.如果正在播放,则直接停止
      // speech.text = this.voiceList.message; // 获取并设置说话时的文本
      // speechSynthesis.speak(speech);
      // setTimeout(()=>{
      //   this.cancel();
      // },5000)
      // let speechData =
    },
    // 暂停
    pause() {
      speechSynthesis.pause();
    },

    // 继续播放
    resume() {
      speechSynthesis.resume();
    },

    // 取消播放
    cancel() {
      speechSynthesis.cancel();
      this.showPop = false;
    },
    logout() {
      //退出到首页
      this.$router.push("/");
      //this.leaveRoom();
    },
  },
};
</script>
  <style scoped>
.dialogBox {
  z-index: 999;
  width: 100%;
  height: 100%;
  background-color: #0000006b;
  position: absolute;
  left: 0rem;
  top: 0rem;
  /* display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  flex-wrap: wrap; */
  /* background-color: rgb(76, 76, 76); */
}
.dialogContainer {
  width: 22rem;
  background-color: white;
  padding-bottom: 1rem;
  position: absolute;
  left: 39rem;
  top: 50%;
  transform: translateY(-50%);
  border-radius: 0.5rem;
  /* width: 22rem;
  padding-bottom: 1rem;
  background-color: red;
  border-radius: 0.7rem;
  position: relative; */
}
.dialogTitle {
  padding: 0.5rem 1rem 0rem;
}
.dialogText {
  margin-top: 2rem;
  color: black;
  line-height: 1.8rem;
  padding-bottom: 2rem;
  text-align: left;
  margin-left: 3rem;
}
.dialogButtonBox {
  margin-top: 1rem;
}
</style>